/**
 * 接口封装
 */
import baseUrl from './basePath.js';
import { getUserInfo } from './utils.js';

const sendRequest = function(param) {
  var _self = this;
  var url = param.url;
  var method = param.method || 'POST';
  var header = {};
  var data = param.data || {};
  var token = '';
  var hideLoading = typeof(data.hideLoading) === 'undefined' ? true : data.hideLoading;
  // 添加用户信息
  data.userid = '';
  let userInfo = getUserInfo();
  if (userInfo) {
    data.userid = userInfo.userid;
  }
  // console.log('ioo', this);
  // 拼接完整请求地址
  var requestUrl = baseUrl + url;

  // 请求方式:GET或POST(POST需配置header: {'content-type' : "application/x-www-form-urlencoded"},)
  if (method) {
    method = method.toUpperCase();// 小写改为大写
    if (method === 'POST') {
      header = {
        'content-type': 'application/x-www-form-urlencoded'
      };
      uni.getStorageSync('token') ? header.token = uni.getStorageSync('token') : null;
    } else {
      header = {'content-type': 'application/json'};
    }
  } else {
    method = 'GET';
    header = {'content-type': 'application/json'};
  }
  // 用户交互:加载圈
  if (hideLoading) {
    uni.showLoading({title: '加载中...'});
  }
  // console.log('网络请求start');
  return new Promise((resolve, reject) => {
    uni.request({
      url: requestUrl,
      method: method,
      header: header,
      sslVerify: false,
      withCredentials: true,
      data: data,
      success: res => {
        // console.log('enter');
        resolve(res.data);
        // console.log("网络请求success:" + JSON.stringify(res));
        // if (res.statusCode && res.statusCode != 200) {//api错误
        //     uni.showModal({
        //         content:"" + res.errMsg
        //     });
        //     return;
        // }
        // if (res.data.code) {//返回结果码code判断:0成功,1错误,-1未登录(未绑定/失效/被解绑)
        //     if (res.data.code == "-1") {
        //         _self.login(backpage, backtype);
        //         return;
        //     }
        //     if (res.data.code != "0") {
        //         uni.showModal({
        //             showCancel:false,
        //             content:"" + res.data.msg
        //         });
        //         return;
        //     }
        // } else{
        //     uni.showModal({
        //         showCancel:false,
        //         content:"No ResultCode:" + res.data.msg
        //     });
        //     return;
        // }
        // typeof param.success == "function" && param.success(res.data);
      },
      fail: (e) => {
        console.log('网络请求fail:' + JSON.stringify(e));
        uni.showModal({
          content: '网络请求出错'
        });
        reject(e.data);
      },
      complete: () => {
        // console.log('网络请求complete');
        if (hideLoading) {
          setTimeout(() => {
						uni.hideLoading();
					}, 0)
        }
        typeof param.complete === 'function' && param.complete();
      }
    });
  });
  // 网络请求
};

export default sendRequest;
